<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat</title>
    <style>
        #messages {
            border: 1px solid #ccc;
            padding: 10px;
            height: 200px;
            overflow-y: scroll;
        }
    </style>
</head>
<body>
<h1>WebSocket Chat</h1>
<div id="messages"></div>
<input type="text" id="messageInput" placeholder="Enter your message">
<button onclick="sendMessage()">Send</button>

<script>
    // 注意这里的端口号应与应用程序配置文件中指定的端口号一致
    let socket = new WebSocket("ws://localhost:8080/ws");

    socket.onopen = function(e) {
        console.log("[open] Connection established");
    };

    socket.onmessage = function(event) {
        console.log(`[message] Data received from server: ${event.data}`);
        let messages = document.getElementById('messages');
        let message = document.createElement('div');
        message.textContent = event.data;
        messages.appendChild(message);
    };

    socket.onclose = function(event) {
        if (event.wasClean) {
            console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
        } else {
            console.log('[close] Connection died');
        }
    };

    socket.onerror = function(error) {
        console.log(`[error] ${error.message}`);
    };

    function sendMessage() {
        let input = document.getElementById('messageInput');
        let message = input.value;
        socket.send(message);
        input.value = '';
    }
</script>
</body>
</html>
